'use strict'
const path = require('node:path')
const log = require('@wjp-cli-dev/log')
const init = require('@wjp-cli-dev/init')
const exec = require('@wjp-cli-dev/exec')
const pkg = require('../package.json')
const colors = require('colors/safe')
const userHome = require('user-home')
const pathExists = require('path-exists').sync
const minimist = require('minimist')
const dotenv = require('dotenv')
const semver = require('semver')
const commander = require('commander')
const constant = require('./const')


let argv, config
async function core (argv) {
  // checkVersion()
  // checkRoot()
  // checkInputArgv()
  await prepare()
  registerCommand(argv)
}
// console.log(process.version)
async function prepare () {
  // checkRoot()
  checkUserHome() //获取用户主目录
  // await checkNpmInfo()  //获取cli版本号 与最新版本比较
  checkEnv()
}
function registerCommand (argv) {
  const program = new commander.Command()
  program
    .name(Object.keys(pkg.bin)[0])
    .usage(` <command> [option]`)
    .version(pkg.version)
    .option('-d --debug', '是否开启debug模式', false)
    .option('-tp --targetPath <targetPath>', '是否指定本地调试文件路径', false)

  program
    .command('init <projectName>')
    .option('-f, --force', '是否强制话初始项目')
    .action(exec)
  const clone = program.command('clone <source> [destination]', {
    // hidden: true //在help中隐藏命令
  })

  // 监听debug模式开启的逻辑
  program.on('option:debug', () => {
    const options = program.opts()
    // console.log('捕获debug', options)
    if (options.debug) {
      process.env.LOG_LEVEL = 'verbose'
    }
    log.level = process.env.LOG_LEVEL
    log.verbose('verbose', '测试')
  })
  // 监听targetPath option
  program.on('option:targetPath', () => {
    const options = program.opts()
    console.log('捕获 targetPath', options.targetPath)
    process.env.CLI_TARGET_PATH = options.targetPath
  })

  // 对未知命令的监听
  program.on('command:*', (obj) => {

    log.error('未知命令：' + obj)
    const availableCommands = program.commands.map((command) => command.name())
    log.info(`可用命令:${availableCommands.join(',')}`)
  })
  console.log(program.args, '222')
  program.parse(process.argv)

  // 当没有输入命令时打印帮助文档
  if (program.args && program.args.length < 1) {
    program.outputHelp()
  }
}

function checkVersion () {
  log.info('cli', colors.yellow(pkg.version))
  console.log(colors.green(pkg.version))
}

function checkRoot () {
  const rootCheck = require('root-check')
  rootCheck()
}

function checkUserHome () {
  // console.log(userHome)
  if (!userHome || !pathExists(userHome)) {
    log.error(colors.red('当前用户目录不存在'))
  }
}

function checkInputArgv () {
  argv = minimist(process.argv.slice(2))
  // console.log(argv)
}

function checkEnv () {
  const dotEnvPath = path.resolve(userHome, '.env')
  // console.log(dotEnvPath)
  if (pathExists(dotEnvPath)) {
    config = dotenv.config({
      path: dotEnvPath
    })
  }
  createDefaultConfig()
  // log.a('环境变量', process.env.CLI_HOME_PATH)
}

function createDefaultConfig () {
  const cliConfig = {
    home: userHome
  }
  // console.log(process.env)
  if (process.env.CLI_HOME) {
    cliConfig.clihome = path.join(userHome, process.env.CLI_HOME)
  } else {
    cliConfig.clihome = path.join(userHome, constant.DEFAULT_CLI_HOME)
  }

  process.env.CLI_HOME_PATH = cliConfig.clihome
  // console.log(process.env)
  return cliConfig
}

async function checkNpmInfo () {
  // 1. 获取当前版本号和模块名
  const npmName = pkg.name
  const currentVersion = pkg.version

  const { getNpmSemverVersion } = require('@wjp-cli-dev/get-npm-info')
  const lastVersion = await getNpmSemverVersion(currentVersion, npmName)
  if (lastVersion && semver.gt(lastVersion, currentVersion)) {
    log.warn('更新提示', '有新版本')
  }
  console.log(lastVersion)
}
module.exports = core